package com.abing.starry.controller;

import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Author CaptainBing
 * @Date 2024/8/25 14:43
 * @Description 微信公众号
 */
@RestController
@RequiredArgsConstructor
public class WxMpController {

    @GetMapping("/")
    public String checkoutWx(String signature, String timestamp, String nonce, String echostr) {
        System.out.println(signature);
        System.out.println(timestamp);
        System.out.println(nonce);
        System.out.println(echostr);
        return echostr;
    }


    @PostMapping("/")
    public String checkoutWxPost(HttpServletRequest request,
                                 String signature,
                                 String timestamp,
                                 String nonce) throws Exception {

        String token = "abing";
        List<String> list = Arrays.asList(token, timestamp, nonce);
        Collections.sort(list);
        String decodeMessage = DigestUtil.digester(DigestAlgorithm.SHA1).digestHex(list.get(0) + list.get(1) + list.get(2));
        System.out.println("wx sign is " + decodeMessage.equals(signature));


        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(request.getInputStream());
        Element rootElement = document.getRootElement();
        Map<String, String> requestMap = new HashMap<>(rootElement.elements().size());
        for (Element element : rootElement.elements()) {
            requestMap.put(element.getName(),element.getText());
        }

        if ("名言".equals(requestMap.get("Content"))) {
            return getMingYan(requestMap);
        }

        if ("笑话".equals(requestMap.get("Content"))) {
            return getJokerMessage(requestMap);
        }

        return getReplyMessage(requestMap);

    }

    private String getReplyMessage(Map<String,String> requestMap){

        String toUserName = requestMap.get("ToUserName");
        String fromUserName = requestMap.get("FromUserName");
        String msgType = requestMap.get("MsgType");
        String content = requestMap.get("Content");

        WxXmlResponseMessage wxXmlResponseMessage = new WxXmlResponseMessage();
        wxXmlResponseMessage.setToUserName(fromUserName);
        wxXmlResponseMessage.setFromUserName(toUserName);
        wxXmlResponseMessage.setCreateTime(System.currentTimeMillis());
        wxXmlResponseMessage.setMsgType(msgType);
        wxXmlResponseMessage.setContent("收到消息:" + content);

        XStream xStream = new XStream();
        xStream.processAnnotations(WxXmlResponseMessage.class);
        String xml = xStream.toXML(wxXmlResponseMessage);
        System.out.println(xml);
        return xml;

    }



    private String getJokerMessage(Map<String,String> requestMap){

        String url = String.format("http://v.juhe.cn/joke/content/list.php?key=964d5983a6019f1ca05e89ba16a9137e&sort=desc&page=1&pagesize=1&time=1418816972");
        String body = HttpUtil.get(url);
        Map bean = JSONUtil.toBean(body, Map.class);
        Map<String,Object> map = (Map<String, Object>) bean.get("result");
        JSONArray data = (JSONArray) map.get("data");
        JSONObject o = (JSONObject) data.get(0);
        Object content = o.get("content");

        String toUserName = requestMap.get("ToUserName");
        String fromUserName = requestMap.get("FromUserName");
        String msgType = requestMap.get("MsgType");
//        String content = requestMap.get("Content");

        WxXmlResponseMessage wxXmlResponseMessage = new WxXmlResponseMessage();
        wxXmlResponseMessage.setToUserName(fromUserName);
        wxXmlResponseMessage.setFromUserName(toUserName);
        wxXmlResponseMessage.setCreateTime(System.currentTimeMillis());
        wxXmlResponseMessage.setMsgType(msgType);
        wxXmlResponseMessage.setContent("收到消息:" + content);

        XStream xStream = new XStream();
        xStream.processAnnotations(WxXmlResponseMessage.class);
        String xml = xStream.toXML(wxXmlResponseMessage);
        System.out.println(xml);
        return body;

    }

    private String getMingYan(Map<String,String> requestMap){

        String url = String.format("http://apis.juhe.cn/fapigx/mingyan/query?num=1&typeid=38&key=ec68122605c743073d78b7ccf08ef677");
        String body = HttpUtil.get(url);
        Map bean = JSONUtil.toBean(body, Map.class);
        Map<String,Object> map = (Map<String, Object>) bean.get("result");
        JSONArray data = (JSONArray) map.get("list");
        JSONObject o = (JSONObject) data.get(0);
        Object content = o.get("content");

        String toUserName = requestMap.get("ToUserName");
        String fromUserName = requestMap.get("FromUserName");
        String msgType = requestMap.get("MsgType");
//        String content = requestMap.get("Content");

        WxXmlResponseMessage wxXmlResponseMessage = new WxXmlResponseMessage();
        wxXmlResponseMessage.setToUserName(fromUserName);
        wxXmlResponseMessage.setFromUserName(toUserName);
        wxXmlResponseMessage.setCreateTime(System.currentTimeMillis());
        wxXmlResponseMessage.setMsgType(msgType);
        wxXmlResponseMessage.setContent(String.valueOf(content).substring(0,3));

        XStream xStream = new XStream();
        xStream.processAnnotations(WxXmlResponseMessage.class);
        String xml = xStream.toXML(wxXmlResponseMessage);
        System.out.println(xml);
        return body;

    }

    @Data
    @XStreamAlias("xml")
    public static class WxXmlResponseMessage {

        @XStreamAlias("ToUserName")
        private String toUserName;

        @XStreamAlias("FromUserName")
        private String fromUserName;

        @XStreamAlias("CreateTime")
        private Long createTime;

        @XStreamAlias("MsgType")
        private String msgType;

        @XStreamAlias("Content")
        private String content;

        @XStreamAlias("MsgId")
        private String msgId;

    }

}


